<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="container">
    <input type="text" name="city" id="city">
    <button id="get-weather">获取天气信息</button>
    <ul>
      <li id="weather"></li>
    </ul>
  </div>

  <script>
    // 获取需要的标签
    var _city = document.querySelector("#city")
    var _btn = document.querySelector("#get-weather")
    var _li = document.querySelector("#weather")

    // 添加事件
    _btn.onclick = function () {

      // 获取城市名称，并判断城市名称不能为空
      var _cityName = _city.value
      if (_cityName.trim() === "") {
        alert("城市名称不能为空")
        return
      }
      console.log(_cityName)

      // Ajax操作
      // 1、创建对象
      var http = new XMLHttpRequest()

      // 2、连接服务器
      http.open('GET', 'https://v0.yiketianqi.com/api?unescape=1&version=v91&appid=43656176&appsecret=I42og6Lm&city=' + _cityName)

      // 3、发送请求
      http.send()

      // 4、处理响应数据
      http.onreadystatechange = function () {
        if (http.readyState === 4 && http.status === 200) {
          // 获取天气数据
          var txt = http.responseText

          // 转换成JSON对象
          var obj = JSON.parse(txt)
          console.log(obj, "获取到的天气信息")

          // DOM操作
          _li.innerText = obj.data[0].narrative
        }
      }
    }
  </script>
</body>

</html>